package com.ruoyi.course.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.course.domain.ClassUserTemplate;
import com.ruoyi.course.domain.ExamClass;
import com.ruoyi.course.domain.ExamClassUser;
import com.ruoyi.course.domain.ExamClassCourse;
import com.ruoyi.course.vo.ExamClassVo;
import com.ruoyi.course.vo.ExamClassUserVo;
import com.ruoyi.course.vo.ExamClassCourseVo;
import com.ruoyi.course.vo.ExamClassDetailVo;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.course.mapper.ExamClassCourseMapper;
import com.ruoyi.course.mapper.ExamClassMapper;
import com.ruoyi.course.mapper.ExamClassUserMapper;
import com.ruoyi.course.service.IExamClassService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import javax.annotation.Resource;

/**
 * 考试班次Service业务层处理
 *
 * @author Tellsea
 * @date 2025-09-26
 */
@Service
public class ExamClassServiceImpl extends ServiceImpl<ExamClassMapper, ExamClass> implements IExamClassService {

    @Resource
    private ExamClassUserMapper examClassUserMapper;

    @Resource
    private ExamClassCourseMapper examClassCourseMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource 
    private SysRoleMapper sysRoleMapper;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Resource
    private ISysConfigService configService;

    @Override
    public TableDataInfo<ExamClassVo> queryList(ExamClassVo entity) {
        return PageUtils.buildDataInfo(this.baseMapper.queryList(PageUtils.buildPage(), entity));
    }

    @Override
    public List<ExamClassVo> queryAll(ExamClassVo entity) {
        return this.baseMapper.queryList(entity);
    }

    @Override
    public ExamClassVo queryById(Long id) {
        return this.baseMapper.queryById(id);
    }

    @Override
    public TableDataInfo<ExamClassUserVo> queryClassStudentList(ExamClassUserVo entity) {
        return PageUtils.buildDataInfo(this.examClassUserMapper.queryClassStudentList(PageUtils.buildPage(), entity));
    }

    @Override
    public TableDataInfo<ExamClassCourseVo> queryClassCourseList(ExamClassCourseVo entity) {
        return PageUtils.buildDataInfo(this.examClassCourseMapper.queryClassCourseList(PageUtils.buildPage(), entity));
    }

    @Override
    public Long importData(List<ClassUserTemplate> studnetList, Long classId) {
        Long result = 0L;
        //查询学员角色id
        SysRole roleQuery = new SysRole();
        roleQuery.setRoleKey("student");
        List<SysRole> sysRoleList = sysRoleMapper.selectRoleList(roleQuery);
        Long studentRoleId = 0L;
        if(sysRoleList.size() > 0) {
            studentRoleId = sysRoleList.get(0).getRoleId();
        }else{
            return result;
        }
        for(ClassUserTemplate studnet : studnetList) {
            //通过用户名查询用户
            SysUser sysUser = sysUserMapper.selectUserByUserName(studnet.getPhone());
            if(sysUser == null) {
                // 新增用户
                SysUser userResult = insertUser(studnet, studentRoleId);
                if(userResult != null) {
                    int classUserResult = insertExamClassUser(classId, userResult.getUserId());
                    if(classUserResult > 0) {
                        result++;
                    }
                }
            }else{
                //更新用户身份证号码字段
                sysUser.setIdCardNumber(studnet.getIdCardNumber());
                sysUserMapper.updateUser(sysUser);
                //新增学员班次关系
                int classUserResult = insertExamClassUser(classId, sysUser.getUserId());
                if(classUserResult > 0) {
                    result++;
                }
            }
        }
        return result;
    }

    /**
     * 新增学员班次
     */
    private int insertExamClassUser(Long classId, Long userId) {
        ExamClassUser examClassUser = new ExamClassUser();
        examClassUser.setClassId(classId);
        examClassUser.setUserId(userId);
        return examClassUserMapper.insert(examClassUser);
    }

    /**
     * 新增用户和学员角色关系
     * @param studnet
     * @return
     */
    private SysUser insertUser(ClassUserTemplate studnet, Long studentRoleId) {
        SysUser sysUser = new SysUser();
        
        // 判断密码逻辑：如果存在身份证号码，密码为身份证号码后六位；否则从配置中获取
        String password;
        if (studnet.getIdCardNumber() != null && !studnet.getIdCardNumber().trim().isEmpty()) {
            // 身份证号码存在，使用后六位作为密码
            String idCard = studnet.getIdCardNumber().trim();
            if (idCard.length() >= 6) {
                password = idCard.substring(idCard.length() - 6);
            } else {
                // 身份证号码长度不足6位，使用整个身份证号码
                password = idCard;
            }
        } else {
            // 身份证号码不存在，从配置服务获取默认密码
            password = configService.selectConfigByKey("sys.user.initPassword");
        }
        sysUser.setUserName(studnet.getPhone());
        sysUser.setNickName(studnet.getUserName());
        sysUser.setPhonenumber(studnet.getPhone());
        sysUser.setStatus("0");
        sysUser.setDelFlag("0");
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        sysUser.setIdCardNumber(studnet.getIdCardNumber());
        if(studnet.getGender().contains("男")) {
            sysUser.setSex("0");
        }else if(studnet.getGender().contains("女"))    {
            sysUser.setSex("1");
        }else{
            sysUser.setSex("2");
        }
        int userResult = sysUserMapper.insert(sysUser);
        if(userResult > 0) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(sysUser.getUserId());
            sysUserRole.setRoleId(studentRoleId);
            sysUserRoleMapper.insert(sysUserRole);
        }else{
            return null;
        }
        return sysUser;
    }

    @Override
    public int removeClassStudent(Long classId, Long userId) {
        ExamClassUser queryEntity = new ExamClassUser();
        queryEntity.setClassId(classId);
        queryEntity.setUserId(userId);
        return examClassUserMapper.delete(new QueryWrapper<>(queryEntity));
    }

    @Override
    public int addClassCourse(Long classId, Long courseId) {
        // 检查关系是否已存在
        QueryWrapper<ExamClassCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("class_id", classId).eq("course_id", courseId);
        
        if (examClassCourseMapper.selectCount(queryWrapper) > 0) {
            // 关系已存在，返回0表示未新增
            return 0;
        }
        
        // 创建新的班次课程关系
        ExamClassCourse examClassCourse = new ExamClassCourse();
        examClassCourse.setClassId(classId);
        examClassCourse.setCourseId(courseId);
        return examClassCourseMapper.insert(examClassCourse);
    }

    @Override
    public int removeClassCourse(Long classId, Long courseId) {
        QueryWrapper<ExamClassCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("class_id", classId).eq("course_id", courseId);
        return examClassCourseMapper.delete(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addClassCourses(Long classId, List<Long> courseIds) {
        if (courseIds == null || courseIds.isEmpty()) {
            return 0;
        }

        int successCount = 0;
        for (Long courseId : courseIds) {
            // 检查关系是否已存在
            QueryWrapper<ExamClassCourse> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("class_id", classId).eq("course_id", courseId);
            
            if (examClassCourseMapper.selectCount(queryWrapper) > 0) {
                // 关系已存在，跳过
                continue;
            }
            
            // 创建新的班次课程关系
            ExamClassCourse examClassCourse = new ExamClassCourse();
            examClassCourse.setClassId(classId);
            examClassCourse.setCourseId(courseId);
            
            int result = examClassCourseMapper.insert(examClassCourse);
            if (result > 0) {
                successCount++;
            }
        }

        return successCount;
    }

    @Override
    public ExamClassDetailVo queryDetailById(Long id) {
        return baseMapper.queryDetailById(id);
    }

    @Override
    public TableDataInfo<ExamClassVo> queryUserClassList(ExamClassVo entity) {
        Long userId = SecurityUtils.getUserId();
        return PageUtils.buildDataInfo(this.baseMapper.queryUserClassList(PageUtils.buildPage(), entity, userId));
    }
}
